# 定义工具函数：判断是否有解 + 自动修复（如无解）
arr = []
with open("D:/UserData/Desktop/seq.txt") as file:
    for line in file:
       arr .append (int(line.replace("\n","")))
print("读取到的数据")
print(arr)
print("{-}".center(64,"-"))
def is_solvable(board):
    size = 4  # for 4x4 puzzle
    flat = board[:]
    blank_index = flat.index(16)
    row_from_bottom = size - (blank_index // size)
    tiles = [x for x in flat if x != 16]

    # Count inversions
    inversions = 0
    for i in range(len(tiles)):
        for j in range(i + 1, len(tiles)):
            if tiles[i] > tiles[j]:
                inversions += 1

    # Determine solvability
    return (inversions + row_from_bottom) % 2 == 0, inversions, row_from_bottom


def make_solvable(board):
    if is_solvable(board)[0]:
        return board  # already solvable
    new_board = board[:]
    i, j = 0, 1
    while new_board[i] == 16:
        i += 1
    while new_board[j] == 16 or j == i:
        j += 1
    # Swap two non-blank tiles to flip inversion parity
    new_board[i], new_board[j] = new_board[j], new_board[i]
    return new_board


# 示例：判断并修复你刚才给的状态
input_board = [13,1,9,2,16,8,10,11,3,4,12,14,15,5,7,6]
input_board = arr
print(f"源{input_board}")
solvable, inversions, row_from_bottom = is_solvable(input_board)
fixed_board = make_solvable(input_board)
print(f"调换后{input_board}")
print(f"返回值{fixed_board}")
print(f"solvable {solvable} inversions {inversions} row_from_bottom {row_from_bottom}")
print(f"{'base1是否有解':<20}, {'逆序和':<3}, {'空白所在行':<6}, 交换后数组的")
print(f'{("true" if solvable else "false"):<23}, {inversions:<5}, {row_from_bottom:<10}, {fixed_board}')


